/* $RCSFile: MenuNavigation.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/MenuNavigation.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Core;
using AddonNice.Diagnostics;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Security;
using AddonNice.Settings;
using AddonNice.Settings.Cache;
using AddonNice.Helpers;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;

namespace AddonNice.UI.WebControls 
{ 

	/// <summary>
	/// Menu navigation inherits from Menu Webcontrol
	/// and adds the 'glue' to link to tabs tree.
	/// </summary>
	public class MenuNavigation : Menu, INavigation , IPortalMenu
	{ 
        PortalSettings _portalSettings; 
        protected PortalSettings portalSettings 
        {
            get 
            {
                if ( _portalSettings == null )
                    _portalSettings = (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
                return _portalSettings;
            }
        }

		#region INavigation implementation 
		private BindOption _bind = BindOption.BindOptionTop; 
		private int _definedParentTab = -1;

		private bool _useTabNameInUrl = false;

		/// <summary> 
		/// Indicates if control should show the tabname in the url 
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool UseTabNameInUrl 
		{ 
			get{return _useTabNameInUrl;} 
			set{_useTabNameInUrl = value;} 
		} 

		private bool _autoBind = false; 

		/// <summary> 
		/// Indicates if control should bind when loads 
		/// </summary> 
		[ 
			Category("Data"), 
				PersistenceMode(PersistenceMode.Attribute) 
		] 
		public bool AutoBind 
		{ 
			get{return _autoBind;} 
			set{_autoBind = value;} 
		} 

		/// <summary> 
		/// Describes how this control should bind to db data 
		/// </summary> 
		[ 
			Category("Data"), 
				PersistenceMode(PersistenceMode.Attribute) 
		] 
		public BindOption Bind 
		{ 
			get {return _bind;} 
			set 
			{ 
				if(_bind != value) 
				{ 
					_bind = value; 
				} 
			} 
		} 

        /// <summary>
		/// defines the parentPageID when using BindOptionDefinedParent
		/// </summary>
		[
			Category("Data"),
				PersistenceMode(PersistenceMode.Attribute)
		]
		public int ParentPageID
		{ 
			get {return _definedParentTab;}
			set
			{
				if(_definedParentTab != value)
				{
					_definedParentTab = value;
				}
			}
		}
		#endregion 

        bool _HideUnderCrm = true;
		/// <summary> 
		/// Should control be hidden when under Crm 
        /// default: true
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool HideUnderCrm
		{ 
			get{return _HideUnderCrm;} 
			set{_HideUnderCrm = value;} 
		} 

        
        bool _IsPortalMenus = false;
		/// <summary> 
		/// Should control act as a portal menu
        /// default: false
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool IsPortalMenus 
		{ 
			get{return _IsPortalMenus;} 
			set{_IsPortalMenus = value;} 
		} 
        
        
        #region IPortalMenu implementation
        
        public void ResetCache()
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation ResetCache BEG Items.Count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
            Cache2.RemoveGlobalPagesCacheKey();
        }

        public void Rebind()
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation Rebind BEG Items.Count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
            Items.Clear();
            InitData();
            if (AutoBind)
                DataBind();
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation Rebind END IsPostBack: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
        }
       
        public bool SelectMenuItem(int wPageId)
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation SelectMenuItem BEG PageId: {0}.", wPageId),NavTraceSwitch.Sw.Info);
            MenuItem it     =    FindItem(wPageId.ToString());
            bool found      =   ( it != null );
            if ( found )
                it.Selected =   true;
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation SelectMenuItem END found: {0}.", found),NavTraceSwitch.Sw.Info);
            return found;
        }

        public Control AjaxControl
        {
            get
            {
                return this;
            }
        }

        public bool ShouldRegisterInAjaxManager
        {
            get
            {
                return true;
            }
        }

        #endregion IPortalMenu

        protected override void OnInit(EventArgs e)
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation OnInit BEG IsPostBack: {0}, AutoBind: {1}.", Page.IsPostBack,AutoBind),NavTraceSwitch.Sw.Info);
            InitData();
            // Registers in portal
            if ( IsPortalMenus )
                portalSettings.AddPortalMenu(this);
            base.OnInit(e);
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation OnInit END count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
        }

        public MenuNavigation() 
		{ 
			EnableViewState    =   true; 
			Load               +=  new EventHandler(LoadControl);
		} 

		private void LoadControl(object sender, EventArgs e) 
		{
            if (!Page.IsPostBack)
            {
                if (AutoBind)
                    DataBind();
            }
		} 

		/// <summary>
		/// Do databind.
		/// </summary>
        protected void InitData()
        {
            // Must hide menu under CRM ??
            if (HideUnderCrm && PortalSettings.IsUnderCRM)
            {
                this.Visible = false;
                return;
            }

            // Build list of tabs to be shown to user 
            int CurrentParentPageID =   -1;
            AuthorizedPageStripDetail authorizedTabs = new AuthorizedPageStripDetail(Bind,ParentPageID,CurrentParentPageID);
            ParentPageID        =   authorizedTabs.ParentPageID;

            bool isForm         =   (Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms );
            IAddonNiceUser    curUser   =   PortalSettings.CurrentUser;
            bool isAuthenticated        =   ( curUser != null ) ? !curUser.IsAnonymous : false;
            for (int i = 0; i < authorizedTabs.Count; i++)
            {
                PageStripDetails myPage = (PageStripDetails)authorizedTabs[i];
                if (( myPage.OkForMenus ) &&
                    ( isForm || ( !isForm && !myPage.FormsOnly ) ) &&
                    ( isAuthenticated || ( !isAuthenticated && !myPage.AuthenticatedOnly ) ) )
                    AddMenuItem(myPage);
            }
        } 

		/// <summary> 
		/// Add a Menu Tree Node if user in in the list of Authorized roles. 
		/// </summary> 
		/// <param name="tabIndex">Index of the tab</param> 
		/// <param name="myPage">Tab to add to the MenuTreeNodes collection</param> 
		protected virtual void AddMenuItem(PageStripDetails myPage) 
		{
            bool okRole             =   PortalSecurity.IsUserInRoles(myPage.AuthorizedRoles);
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation AddMenuItem PageName: {0}, PageID: {1}, OkRole: {2}, Roles: {3}", 
                    new object[] { myPage.PageName, myPage.PageID, okRole, myPage.AuthorizedRoles }),NavTraceSwitch.Sw.Info);
            if (okRole) 
			{
                MenuItem mn         =   new MenuItem(myPage.PageKeyPhrase, myPage.PageID.ToString());
                if ( myPage.PageID == StStr.WelcomePageID ) // We track Welcome Page to Add the Portal Name
                    mn.Text         =   string.Format("{0} {1}",myPage.PageKeyPhrase,portalSettings.PortalName);
                if ( NavTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation AddMenuItem PageName: {0}, PageID: {1}", myPage.PageName,myPage.PageID),NavTraceSwitch.Sw.Info);

                mn                  =   RecurseMenu(myPage.Pages, mn);
                // Tab with Id 0 and Tabs without children are url's Tabs
                if ( myPage.PageID == StStr.PageIDNotAssigned || mn.ChildItems.Count == 0)
                {
                    mn.NavigateUrl  =   MenuHelper.GiveMeUrl(myPage.PageKeyPhrase, myPage.PageID,myPage.Flags,UseTabNameInUrl);
                    mn.Selectable   =   (mn.NavigateUrl == string.Empty) ? false:true;
                }
                else mn.Selectable  =   false;
                this.Items.Add(mn);
            } 
		} 
		/// <summary>
		/// 
		/// </summary>
        protected virtual MenuItem RecurseMenu(PageStripDetailsList t, MenuItem mn) 
		{ 
			if (t.Count > 0) 
			{ 
                bool isForm                 =   (Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms );
                IAddonNiceUser    curUser   =   PortalSettings.CurrentUser;
                bool isAuthenticated        =   ( curUser != null ) ? !curUser.IsAnonymous : false;
				for (int c=0; c < t.Count; c++) 
				{ 
					PageStripDetails mySubTab = t[c];
                    if ( !mySubTab.OkForMenus )
                        continue;
                    if ( !isForm && mySubTab.FormsOnly)
                        continue;
                    if ( !isAuthenticated && mySubTab.AuthenticatedOnly )
                        continue;
                    if ( NavTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MenuNavigation RecurseMenu mySubTab.PageName: {0}, PageID: {1}", mySubTab.PageName, mySubTab.PageID),NavTraceSwitch.Sw.Info);
                    if (PortalSecurity.IsUserInRoles(mySubTab.AuthorizedRoles)) 
					{
                        MenuItem mnc        =   new MenuItem(mySubTab.PageKeyPhrase, mySubTab.PageID.ToString());
                        mnc                 =   RecurseMenu(mySubTab.Pages, mnc);
                        if (mnc.ChildItems.Count == 0)
                        {
                            mnc.NavigateUrl =   MenuHelper.GiveMeUrl(mySubTab.PageKeyPhrase, mySubTab.PageID,mySubTab.Flags,UseTabNameInUrl);
                            mnc.Selectable  =   (mnc.NavigateUrl == string.Empty) ? false : true;
                        }
                        else mnc.Selectable =   false;
                        mn.ChildItems.Add(mnc);
                    } 
				} 
			} 
			return mn; 
		}
	} 
}